import React, { createContext, ReactElement } from 'react';
import { State, Action, Context } from './types';
import actions, { getReload } from './actions';
import Provider from '../../components/Provider';

export const initialState: State = {
  productId: 0,
  productInfo: {
    productName: '',
    startTime: '',
    endTime: '',
    timeDuration: 0,
    headImage: '',
    detailImages: [],
    skus: [],
    soldNum: 0,
    teacherWechat: ''
  },
  priceInfo: {
    oldPrice: -1,
    newPrice: -1
  },
  selectedSkuIds: [],
  isShowSkus: false,
  spuInfo: {
    showPrice: 0,
    realPrice: 0,
    commodityName: '',
    startTime: '',
    duration: 0,
    showImages: [],
    hasPackage: false
  },
  isFetchFailed: false
};

export const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case 'SET_PRODUCT_ID':
      return { ...state, productId: action.value };
    case 'SET_PRODUCT_INFO':
      return {
        ...state,
        productInfo: action.value,
        selectedSkuIds: [],
        isShowSkus: false,
        isFetchFailed: false
      };
    case 'SET_REAL_PRICE':
      return { ...state, priceInfo: action.value };
    case 'SET_SELECTED_IDS':
      return { ...state, selectedSkuIds: action.value };
    case 'SET_IS_SHOW_SKUS':
      return { ...state, isShowSkus: action.value };
    case 'SET_SPU_INFO':
      return { ...state, spuInfo: action.value };
    case 'FETCH_FAILED':
      return { ...state, isFetchFailed: true };
    default:
      return state;
  }
};

export const Store = createContext<Context>({
  state: initialState
});

export default (props: { [key: string]: any }): ReactElement => {
  return (
    <Provider
      reducer={reducer}
      initialState={initialState}
      Store={Store}
      actions={actions}
      reload={getReload}
      {...props}
    />
  );
};
